const db = require('../../utils/dbUtil');

class User {
    constructor() {
    }

    loadUser(username) {
        return db.query('select * from admin where name = ?;', [username]);
    }

    getUserCount() {
        return db.queryForInt('select count(1) from admin ;');
    }

    getUserList(index, limit) {
        return db.query('select * from admin limit ?,?;', [index * limit, limit]);
    }

    addUser(user) {
        return db.insert('insert into admin (name,password,role_name,image,privilege,description,disabled,time,update_time) values(?,?,?,?,?,?,?,?,?);', [user.name, user.password, user.role_name, user.image, user.privilege, user.description, user.disabled,Date.now(), Date.now()]);
    }

    updateUser(user) {
        return db.update('update admin set role_name = ?,privilege = ?,description = ?,update_time = ?,disabled=? where name = ?;', [user.role_name, user.privilege, user.description, Date.now(), user.disabled, user.name]);
    }

    loginSuccess(username){
        return db.update('update admin set time = ? where name = ?;',[Date.now(),username]);
    }

    changePassword(username, password) {
        return db.update('update admin set password = ?,update_time = ? where name = ?;', [password, Date.now(), username]);
    }

    changeAvatar(username, img_url) {
        return db.update('update admin set image = ?,update_time = ? where name = ?;', [img_url, Date.now(), username]);
    }

    deleteUser(username, admin_id) {
        var promise = new Promise(function (resolve, reject) {
            db.beginTransaction().then(connection => {
                connection.query("delete from admin where name = ? ;", [username], (err, results) => {
                    if (err) {
                        db.rollback(connection);
                        reject(err);
                    }

                    connection.query('delete from menu_auth where admin_id = ?;', [admin_id], err1 => {
                        if (err1) {
                            db.rollback(connection);
                            reject(err1);
                        }

                        db.commit(connection);
                        resolve(results.affectedRows || 0);
                    });

                });
            }).catch(err => reject(err));
        });
        return promise;
    }
}


User.state = {
    ENABLED: 0,
    DISABLED: 1
}

module.exports = new User();